{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cf3f1b0c-a8f3-49e5-95ae-5febbcb42908",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-11-18T12:25:46.977562Z",
     "iopub.status.busy": "2025-11-18T12:25:46.977351Z",
     "iopub.status.idle": "2025-11-18T12:25:46.982405Z",
     "shell.execute_reply": "2025-11-18T12:25:46.981979Z",
     "shell.execute_reply.started": "2025-11-18T12:25:46.977546Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "llm 调用 tools,让llm 和外界交流\n"
     ]
    }
   ],
   "source": [
    "print(\"llm 调用 tools,让llm 和外界交流\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b9a29b82-aef6-433a-8eca-63731544882d",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2025-11-18T12:27:30.388138Z",
     "iopub.status.busy": "2025-11-18T12:27:30.387915Z",
     "iopub.status.idle": "2025-11-18T12:27:38.751019Z",
     "shell.execute_reply": "2025-11-18T12:27:38.750486Z",
     "shell.execute_reply.started": "2025-11-18T12:27:30.388120Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.cloud.aliyuncs.com/pypi/simple\n",
      "Requirement already satisfied: requests in /usr/local/lib/python3.11/site-packages (2.32.3)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/site-packages (from requests) (3.4.1)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/site-packages (from requests) (3.10)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/site-packages (from requests) (2.3.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/site-packages (from requests) (2025.1.31)\n",
      "\u001b[33mDEPRECATION: pytorch-lightning 1.7.7 has a non-standard dependency specifier torch>=1.9.*. pip 24.0 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pytorch-lightning or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.3.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.3\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
      "Looking in indexes: https://mirrors.cloud.aliyuncs.com/pypi/simple\n",
      "Requirement already satisfied: openai in /usr/local/lib/python3.11/site-packages (2.3.0)\n",
      "Requirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.11/site-packages (from openai) (4.11.0)\n",
      "Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.11/site-packages (from openai) (1.9.0)\n",
      "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.11/site-packages (from openai) (0.28.1)\n",
      "Requirement already satisfied: jiter<1,>=0.10.0 in /usr/local/lib/python3.11/site-packages (from openai) (0.11.0)\n",
      "Requirement already satisfied: pydantic<3,>=1.9.0 in /usr/local/lib/python3.11/site-packages (from openai) (2.11.10)\n",
      "Requirement already satisfied: sniffio in /usr/local/lib/python3.11/site-packages (from openai) (1.3.1)\n",
      "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.11/site-packages (from openai) (4.67.1)\n",
      "Requirement already satisfied: typing-extensions<5,>=4.11 in /usr/local/lib/python3.11/site-packages (from openai) (4.15.0)\n",
      "Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.11/site-packages (from anyio<5,>=3.5.0->openai) (3.10)\n",
      "Requirement already satisfied: certifi in /usr/local/lib/python3.11/site-packages (from httpx<1,>=0.23.0->openai) (2025.1.31)\n",
      "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/site-packages (from httpx<1,>=0.23.0->openai) (1.0.9)\n",
      "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.11/site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.16.0)\n",
      "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)\n",
      "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai) (2.33.2)\n",
      "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai) (0.4.2)\n",
      "\u001b[33mDEPRECATION: pytorch-lightning 1.7.7 has a non-standard dependency specifier torch>=1.9.*. pip 24.0 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pytorch-lightning or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.3.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.3\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "# npm install\n",
    "# 发起请求\n",
    "!pip install requests\n",
    "!pip install openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5dc4e7f7-85d0-45a0-aa6c-a054cc5d2386",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2025-11-18T12:50:46.568018Z",
     "iopub.status.busy": "2025-11-18T12:50:46.567798Z",
     "iopub.status.idle": "2025-11-18T12:50:46.625948Z",
     "shell.execute_reply": "2025-11-18T12:50:46.625576Z",
     "shell.execute_reply.started": "2025-11-18T12:50:46.568004Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'results': [{'location': {'id': 'WSFXR95RZD21', 'name': '抚州', 'country': 'CN', 'path': '抚州,抚州,江西,中国', 'timezone': 'Asia/Shanghai', 'timezone_offset': '+08:00'}, 'now': {'text': '阴', 'code': '9', 'temperature': '8'}, 'last_update': '2025-11-18T20:37:05+08:00'}]}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'抚州当前天气：阴, 气温8度'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests\n",
    "# python 类型约定\n",
    "# js 弱类型语言\n",
    "# -> str 返回值的类型\n",
    "def get_weather(location: str) -> str:\n",
    "    url = \"https://api.seniverse.com/v3/weather/now.json\"\n",
    "    params = {\n",
    "        \"key\":\"SHkmTx-XYyfPOja87\",\n",
    "        \"location\":location,\n",
    "        \"language\":\"zh-Hans\"\n",
    "    }\n",
    "    try:\n",
    "        resp = requests.get(url,params=params,timeout=10)\n",
    "        data = resp.json()\n",
    "        print(data)\n",
    "        if \"results\" in data:\n",
    "            r = data[\"results\"][0]\n",
    "            city = r[\"location\"][\"name\"]\n",
    "            # 当前对象天气\n",
    "            now = r[\"now\"]\n",
    "            text = now[\"text\"]\n",
    "            temp = now[\"temperature\"]\n",
    "            # python 擅长机器学习 和字符处理\n",
    "            return f\"{city}当前天气：{text}, 气温{temp}度\"\n",
    "        else:\n",
    "            return \"查询失败\"\n",
    "    except Exception as e:\n",
    "        return f\"异常: {e}\"\n",
    "    \n",
    "get_weather(\"抚州\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "64ab8423-70b7-46bf-b9b3-d9a2ecfedf89",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-11-18T12:55:44.227109Z",
     "iopub.status.busy": "2025-11-18T12:55:44.226899Z",
     "iopub.status.idle": "2025-11-18T12:55:44.672120Z",
     "shell.execute_reply": "2025-11-18T12:55:44.671649Z",
     "shell.execute_reply.started": "2025-11-18T12:55:44.227094Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 用户user向llm 提问 自然语言\n",
    "# 实时性的，工具类的，llm 无法回答\n",
    "# llm和原有的互联网文明桥接起来？智能互联网来了\n",
    "# tools 来自openai 接口定义，\n",
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key='sk-10a0f9cbf8fd4a65ae5cdb08925b0872',\n",
    "    base_url='https://api.deepseek.com/v1'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "7665168e-40ad-4d4a-b230-c6db3645a136",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2025-11-18T13:15:56.377324Z",
     "iopub.status.busy": "2025-11-18T13:15:56.377121Z",
     "iopub.status.idle": "2025-11-18T13:15:56.380258Z",
     "shell.execute_reply": "2025-11-18T13:15:56.379852Z",
     "shell.execute_reply.started": "2025-11-18T13:15:56.377310Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# openai 接口定义\n",
    "tools = [\n",
    "    # JSON 定义\n",
    "    {\n",
    "        # 一个工具就是一个函数\n",
    "        \"type\":\"function\",\n",
    "        # 函数的声明\n",
    "        \"function\": {\n",
    "            \"name\":\"get_weather\",\n",
    "            \"description\":\"获取指定城市的当前天气\",\n",
    "            \"parameters\":{\n",
    "                \"type\":\"object\",\n",
    "                \"properties\":{\n",
    "                    \"location\":{\n",
    "                        \"type\":\"string\",\n",
    "                        # 北京天气怎么样？提取出来北京\n",
    "                        \"description\":\"城市名称，如'北京'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"location\"]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "8e2c1b37-a830-4fa1-871f-ebe459f0c606",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2025-11-18T13:34:41.082411Z",
     "iopub.status.busy": "2025-11-18T13:34:41.082189Z",
     "iopub.status.idle": "2025-11-18T13:34:47.536675Z",
     "shell.execute_reply": "2025-11-18T13:34:47.536212Z",
     "shell.execute_reply.started": "2025-11-18T13:34:41.082397Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ChatCompletionMessage(content='我来帮您查询北京的天气情况。', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=[ChatCompletionMessageFunctionToolCall(id='call_00_N1u5DNX5vKqOAutbIW6orZrY', function=Function(arguments='{\"location\": \"北京\"}', name='get_weather'), type='function', index=0)])\n",
      "{'results': [{'location': {'id': 'WX4FBXXFKE4F', 'name': '北京', 'country': 'CN', 'path': '北京,北京,中国', 'timezone': 'Asia/Shanghai', 'timezone_offset': '+08:00'}, 'now': {'text': '晴', 'code': '1', 'temperature': '3'}, 'last_update': '2025-11-18T21:27:31+08:00'}]}\n",
      "根据查询结果，北京当前天气情况如下：\n",
      "\n",
      "- **天气状况**：晴\n",
      "- **温度**：3°C\n",
      "\n",
      "今天北京天气晴朗，但气温较低，建议您：\n",
      "- 外出时注意保暖，穿上厚外套\n",
      "- 由于天气干燥，多补充水分\n",
      "- 早晚温差可能较大，注意适时增减衣物\n",
      "\n",
      "如果您需要了解未来几天的天气预报，或者想了解其他地区的天气情况，随时告诉我！\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "messages = [{\"role\":\"user\",\"content\":\"北京天气怎么样\"}]\n",
    "response = client.chat.completions.create(\n",
    "    model = 'deepseek-reasoner',\n",
    "    messages = messages,\n",
    "    tools = tools,\n",
    "    tool_choice = \"auto\",\n",
    "    # 生成的随机度\n",
    "    temperature = 0.3\n",
    ")\n",
    "response_message = response.choices[0].message\n",
    "print(response_message)\n",
    "# tool_calls ChatCompletionMessageFuntionToolcall\n",
    "messages.append(response_message)\n",
    "if response_message.tool_calls:\n",
    "    for tool_call in response_message.tool_calls:\n",
    "        function_name = tool_call.function.name\n",
    "        # json 字符串变成json 对象\n",
    "        function_args = json.loads(tool_call.function.arguments)\n",
    "        if function_name == \"get_weather\":\n",
    "            function_response = get_weather(function_args[\"location\"])\n",
    "        else:\n",
    "            function_response = \"未知工具\"\n",
    "        messages.append({\n",
    "                \"tool_call_id\": tool_call.id,\n",
    "                \"role\":\"tool\",\n",
    "                \"name\": function_name,\n",
    "                \"content\": function_response\n",
    "            })\n",
    "else:\n",
    "    print(response_message.content)\n",
    "\n",
    "final_response = client.chat.completions.create(\n",
    "    model = \"deepseek-reasoner\",\n",
    "    messages = messages,\n",
    "    temperature = 0.3\n",
    ")\n",
    "print(final_response.choices[0].message.content)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
